define(['jquery'], function ($) {
    // toast的开关：防止连续快速点击时显示多个重复的toast在页面上
    var toastFlag = false;
    var app= {
        /**
         * 获取地址栏查询参数的值
         * @param name
         * @returns {any}
         */
        getUrlParam: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var result = window.location.search.substr(1).match(reg);
            return result ? decodeURIComponent(result[2]) : null;
        },

        /**
         * 获取路由参数
         */
        getUrlParams: function () {
            var hashDeatail = location.hash.split("?"),
                hashName = hashDeatail[0].split("#")[1],//路由地址
                params = hashDeatail[1] ? hashDeatail[1].split("&") : [],//参数内容
                query = {};
            for (var i = 0; i < params.length; i++) {
                var item = params[i].split("=");
                query[item[0]] = item[1];
            }
            return {
                path: hashName,
                query: query
            };
        },

        /**
         * 时间戳转日期
         * @param value 值
         * @param emptyFormatterFlag 传 true 时,返回空, 默认返回两个--
         * @param flag 传 true 时,返回含时分秒, 默认返回不包含时分秒
         * @returns {string}
         */
        dateTimeFormatter: function (value, emptyFormatterFlag, flag) {
            value = Number(value);
            if (value === 0) {
                if (emptyFormatterFlag) {
                    return '';
                } else {
                    return "--";
                }
            }
            var date = new Date(value * 1000);
            var y = date.getFullYear();
            var mo = date.getMonth() < 9 ? '0' + (date.getMonth() - 0 + 1) : date.getMonth() - 0 + 1;
            var d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
            var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
            var mi = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
            var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            if(flag) {
                return y + "-" + mo + "-" + d + " " + h + ":" + mi + ":" + s;
            } else {
                return y + "-" + mo + "-" + d;
            }
        },

        /**
         * 获取当天时间
         * @returns {string}
         */
        getTodayDate: function () {
            var date = new Date();
            var y = date.getFullYear();
            var mo = date.getMonth() < 9 ? '0' + (date.getMonth() - 0 + 1) : date.getMonth() - 0 + 1;
            var d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
            return y + "-" + mo + "-" + d;
        },

        /**
         * 获取过去或未来n天的时间
         * @param day 正数为未来，负数为过去
         * @returns {string}
         */
        getDay: function (day) {
            var today = new Date();
            var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
            today.setTime(targetday_milliseconds);
            var tYear = today.getFullYear();
            var tMonth = today.getMonth() < 9 ? '0' + (today.getMonth() - 0 + 1) : today.getMonth() - 0 + 1;
            var tDate = today.getDate() < 10 ? '0' + today.getDate() : today.getDate();
            return tYear + "-" + tMonth + "-" + tDate;
        },

        /**
         * 封装ajax请求
         * @param param
         */
        request: function (param) {
            $.ajax({
                type: param.type || "POST",
                url: param.url || "",
                data: param.data || "",
                // 如果给服务端传递json数据需要设置成'application/json;charset=UTF-8'
                contentType: param.contentType || "application/x-www-form-urlencoded; charset=UTF-8",
                dataType: param.dataType || "json",
                async: param.async === undefined,
                success: function (res) {
                    if (res.code === 0) {
                        typeof param.success === "function" && param.success(res.data, res.msg, res);
                    } else if (param.error === "function") {
                        param.error(res.msg);
                    }
                },
                error: function (err) {
                    if (err.status === 401) {
                        $.get("ignore/psdLogin", function (res) {
                            window.location.href = res.data;
                        });
                    } else if (param.error === "function") {
                        param.error(err.statusText);
                    } else {
                        app.errorTip(err.status + "：" + err.statusText);
                    }
                }
            });
        },

        /**
         * 封装提示信息弹窗
         * @param msg 提示信息
         * @param type 提示类型
         * @param timeout 提示时间
         */
        toast: function (msg, type, timeout) {
            if (!!!msg) {
                msg = "操作失败";
            }
            if (!!!type) {
                type = "danger";
            }
            if (!!!timeout) {
                timeout = 3000;
            }
            if (!toastFlag) {
                toastFlag = true;
                Dialog.toast(msg, {
                    intent: type, timeout: timeout, onDismiss: function () {
                        toastFlag = false;
                    }
                });
            }
        },
        successTip: function (msg, timeout) {
            this.toast(msg || "操作成功", "success", timeout);
        },
        errorTip: function (msg, timeout) {
            this.toast(msg || "操作失败", "danger", timeout);
        },

        /**
         * 通过form表单下载文件
         * @param url 下载的接口地址
         * @param params 需要的参数 eg. {key1:value1,key2:value2}
         */
        downloadByForm: function (url, params) {
            var form = document.createElement("form");
            form.style.display = "none";
            form.action = url;
            form.method = "post";
            document.body.appendChild(form);
            for (var key in params) {
                var input = document.createElement("input");
                input.type = "hidden";
                input.name = key;
                input.value = params[key];
                form.appendChild(input);
            }
            form.submit();
            form.remove();
        },

        /**
         * POST接口下载
         * @param url 接口路径
         * @param params 传参
         * @param fileName 下载的文件名
         */
        downloadFile: function (url, params, fileName) {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", url, true);
            if (typeof params === 'object') {
                params = JSON.stringify(params);
                xhr.setRequestHeader("Content-type", "application/json");
            } else {
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded;");
            }
            xhr.responseType = "blob";
            xhr.onreadystatechange = function () {
                var XMLHttpReq = xhr;
                if (XMLHttpReq.readyState === 4) {
                    if (XMLHttpReq.status === 200) {
                        if (xhr.getResponseHeader("Content-Type") === "application/json;charset=UTF-8") {
                            Dialog.toast("文件下载失败！", {"intent": "danger"});
                            return;
                        }
                        var blobURL = window.URL.createObjectURL(XMLHttpReq.response);
                        var tempLink = document.createElement("a");
                        tempLink.style.display = "none";
                        tempLink.href = blobURL;
                        tempLink.setAttribute("download", fileName);
                        
                        if (typeof tempLink.download === "undefined") {
                            tempLink.setAttribute("target", "_blank");
                        }

                        document.body.appendChild(tempLink);
                        tempLink.click();
                        document.body.removeChild(tempLink);
                        window.URL.revokeObjectURL(blobURL);
                    }
                }
            };
            xhr.send(params);
        },

        /**
         * 将form表单数据序列化成对象
         * @param formId
         */
        serializeObject: function (formId) {
            var data = {};
            var array = $("#" + formId).serializeArray();
            $(array).each(function () {
                if (data[this.name]) {
                    if ($.isArray(data[this.name])) {
                        data[this.name].push(this.value);
                    } else {
                        data[this.name] = [data[this.name], this.value];
                    }
                } else {
                    data[this.name] = this.value;
                }
            });
            return data;
        },

        /**
         * 获取假盘对应按键的keyCode
         */
        getKeyCode: function (keyName) {
            keyName = keyName.toUpperCase();
            var KEYS = {
                BACKSPACE: 8,
                TAB: 9,
                ENTER: 13,
                SHIFT: 16,
                CTRL: 17,
                ALT: 18,
                ESC: 27,
                SPACE: 32,
                PAGE_UP: 33,
                PAGE_DOWN: 34,
                END: 35,
                HOME: 36,
                LEFT: 37,
                UP: 38,
                RIGHT: 39,
                DOWN: 40,
                DELETE: 46
            };
            return KEYS[keyName];
        },

        /**
         * 防xss攻击
         */
        __htmlEscapeEntities: function (d) {
            return typeof d === "string" ?
                d.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;") :
                d;
        },

        /**
         * html转码
         */
        __htmlReturn: function (d) {
            return typeof d === "string" ?
                d.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#039;/g, "\'") :
                d;
        },

        /**
         * 根据laydate的value值返回起始和结束时间的时间戳
         * @param laydateValue eg. "2020-04-06 - 2020-04-10"
         * @returns {startTime: string, endTime: string} 返回起始时间和结束时间的时间戳 （开始时间以00:00:00开始，结束时间以23:59:59结束）
         */
        getTimeRange: function (laydateValue) {
            var timeRange = {
                startTime: "",
                endTime: ""
            };
            if (laydateValue) {
                timeRange.startTime = new Date(laydateValue.substring(0, 10) + " 00:00:00").getTime() / 1000;
                timeRange.endTime = new Date(laydateValue.substring(13) + " 23:59:59").getTime() / 1000;
            }
            return timeRange;
        },

        /**
         * 获取select2选中的值
         * @param dom
         * @returns {Array}
         */
        getSelect2Data: function (id) {
            var ret = [];
            ret = $(id).select2("data").map(function (item) {
                return {
                    id: item.id,
                    text: item.text
                };
            });
            return ret;
        },
        getSelect2Id: function (id) {
            return _.map(app.getSelect2Data(id), "id")[0];
        },
        getSelect2Text: function (id) {
            return _.map(app.getSelect2Data(id), "text")[0];
        },
        // 针对JSON.parse的错误处理
        jsonParse: function (str) {
            return _.attempt(JSON.parse.bind(null, str));
        },
        // 获取页面名称
        getPageName: function () {
            var pageName = location.pathname.substring(location.pathname.lastIndexOf("\/") + 1) || "";
            return pageName;
        },

        /**
         * 需要加权限控制的元素加上hidden隐藏和data-can-权限
         * 获取那些元素可以访问，然后移除hidden
         * 根据权限显示隐藏的元素
         * @param pageName
         */
        showElemByAuth: function (pageName) {
            var name = ""; // 页面名称
            if (pageName) {
                name = pageName;
            } else {
                name = app.getPageName();
            }
            var aKnowledgeBaseAuth = app.jsonParse(sessionStorage.getItem("aKnowledgeBaseAuth"));
            var elemAuth = _.pluck(_.find(aKnowledgeBaseAuth, "optId", name).children, "optId");
            var style = document.createElement("style");
            style.type = "text/css";
            var cssString = "";
            _.forEach(elemAuth, function (v, i) {
                cssString += " .auth-" + v + " {visibility:visible!important;width: unset;height: unset;overflow: unset;position:initial}";
            });
            style.innerHTML = cssString;
            document.head.appendChild(style);
        },
        /**
         * 显示点点点
         * @param source {String}
         * @param len {Number} 显示len个字
         * @param isNeedEnd {Boolean}
         * @returns {String}
         */
        ell: function (source, len, isNeedEnd) {
            var retStr = "";
            if (source != undefined && source != "undefined" && source != "") {
                var sourceLen = source.length;
                if (isNeedEnd) {
                    retStr = sourceLen > len ? source.substr(0, len) + "..." : source;
                } else {
                    retStr = sourceLen > len ? source.substr(0, len) : source;
                }
            }

            return retStr;
        },
        /**
         * 删除前面len位字符，返回剩下的
         * @param source
         * @param len
         * @returns {string}
         */
        delStrHead: function (source, len) {
            var retStr = "";
            if (source != undefined && source != "undefined" && source != "") {
                var sourceLen = source.length;
                retStr = sourceLen > len ? source.substr(len, source.length) : source;
            }
            return retStr;
        },
        /**
         * 替换特殊字符
         * @param str
         * @returns {String}
         */
        replaceHtml: function (str) {
            var retStr = "";
            if (str != undefined && str != "undefined" && str != "") {
                retStr = str.replace(/&/ig, "&amp;")
                    .replace(/\"|\\\"/ig, "&quot;")
                    .replace(/\\n|\\\\n/ig, "&nbsp;")
                    .replace(/'/ig, "&#039;")
                    .replace(/</ig, "&lt;")
                    .replace(/>/ig, "&gt;");
            }

            return retStr;
        },
        /**
         * 移除字符串尾部的字符
         * @param s
         * @returns {string}
         */
        delLastChar: function (str) {
            str = str.trim();
            str = str.substring(0, str.length - 1);
            return str;
        },
        /**
         * 移除字符串首尾的字符
         * @param s
         * @returns {string}
         */
        delFirstAndLastChar: function (s) {
            var ret = "";
            s = s.trim();
            ret = s.substr(1).substring(0, s.length - 2);
            return ret;
        },
        /**
         * 移除字符串中的html标签
         * @param htmlStr
         * @returns {string|*}
         */
        removeHtmlTag: function (htmlStr) {
            if (htmlStr) {
                var str = htmlStr.replace(/<[^>]+>/g, "");
                return str;
            } else {
                return "";
            }
        },
        /**
         * 从数组中获取索引为奇数的元素返回一个新数组
         * @param arr
         * @returns {*}
         */
        getOddFromArray: function (arr) {
            var oddArr = arr.filter(function (item, i) {
                return i % 2 !== 0;
            });
            return oddArr;
        },
        /**
         * 从数组中获取索引为偶数的元素返回一个新数组
         * @param arr
         * @returns {*}
         */
        getEvenFromArray: function (arr) {
            var evenArr = arr.filter(function (item, i) {
                return i % 2 == 0;
            });
            return evenArr;
        },
        /**
         * 单位转换
         * @param num
         * @returns string
         */
        tmpNum: function (num) {
            if (100000000 > num && num > 9999) {
                num = (num / 10000).toFixed(2) + "万";
            } else if (num > 99999999 && num < 9999999999) {
                num = (num / 100000000).toFixed(2) + "亿";
            } else if (num > 99999999999) {
                num = (num / 100000000000).toFixed(2) + "千亿";
            } else {
                num = num.toString();
            }
            return num;
        },
        /**
         * 数字形式转换（每三位增加间隔符）
         * @param num
         * @returns {string}
         */
        tranNumber: function (num) {
            var number = num.toString();
            var len = 3; // 每隔几位数字插入分隔符
            var numberStr = ""; // 返回的数字
            var numberArr = number.split("");
            var tempStr = "";
            numberArr.forEach(function (v, i) {
                if (i != 0 && (numberArr.length - i) % len == 0) {
                    tempStr += "," + v;
                } else {
                    tempStr += v;
                }
            });
            numberStr = tempStr;
            return numberStr;
        },
    };
    return app;
});